import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';
import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/entity/home/AlbumEntity.dart';
import 'package:qianyi/entity/home/album_detail_list_entity.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:quds_ui_kit/screens/quds_bottom_sheet_container.dart';
import 'dart:io'; // 导入dart:io库以使用File类

import '../../../../controller/homeTabController.dart';
import '../../../../controller/imageDetailVideoController.dart';
import '../../../../entity/mine/User.dart';
import '../../../../network/http_config.dart';
import '../../../../network/http_entity.dart';
import '../../../../state/token.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../utils/DialogUtils.dart';
import '../../../../utils/throttle.dart';
import '../../../../view_model/home/AlbumDetailListModel.dart';
import '../../../../view_model/mine/album_view_model.dart';
import '../../../../wcao/ui/theme.dart';
import 'package:dio/dio.dart' as dio;


class EditAlbumScreen extends StatefulWidget {
  @override
  _AlbumScreenState createState() => _AlbumScreenState();
}

class _AlbumScreenState extends State<EditAlbumScreen> {
  HomeTabController homeTabController = Get.find();
  TokenController tokenController = Get.find();
  AlbumEntity? albumEntity;
  TextEditingController textEditingController = TextEditingController();
  TextEditingController textEditingController1 = TextEditingController();
  final picker = ImagePicker();
  final FocusNode focusNode = FocusNode();
  final FocusNode focusNode1 = FocusNode();
  XFile? xFile;

  List<String> images = [
    'https://example.com/image1.jpg', // 替换为实际图片链接
    'https://example.com/image2.jpg', // 替换为实际图片链接
    // 添加更多图片链接...
  ];
  @override
  void initState() {
    getAlbumEntity();
    // TODO: implement initState
    super.initState();
  }
  getAlbumEntity() async {
    HudUtil.showBeautiful(context);
    Map<String,String> params1 = {
      "id":homeTabController.albumDetailId
    };
    HttpEntity httpEntity1 = await HttpManager.getInstance().request(url: '/platform/album/getAlbum',params: params1,method: Method.get) as HttpEntity;
    setState(() {
      albumEntity = AlbumEntity.fromJson(httpEntity1.getOriData()['data']);

    });
    HudUtil.dismiss();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("修改专辑"),

      ),
      body:  albumEntity != null? Padding(padding: EdgeInsets.all(10),
          child: ListView(
            children: [
              xFile!=null?
              Image.file(
                File(xFile!.path),
                height: 300,
                width: 300,
                fit: BoxFit.cover,
              ):
              FancyShimmerImage(imageUrl: albumEntity!.cover!),

              SizedBox(height: 8,),

              TextField(
                focusNode: focusNode,
                maxLength: 50,
                minLines:3,
                controller: textEditingController,
                decoration: InputDecoration(
                  hintText: '${albumEntity!.name==null?'修改你的简介':albumEntity!.name}',
                  border: InputBorder.none,
                ),
                onEditingComplete: () {

                },
                onChanged: (e) {
                  // this.content = e;
                },
                onSubmitted: (e) {},
                onTap: () {

                },
                maxLines: null,
              ),
              SizedBox(
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      MaterialButton(
                        onPressed: () async {

                          xFile = await picker.pickImage(source: ImageSource.gallery, maxHeight: 1080, maxWidth: 1080);
                          File oriFile = new File(xFile!.path);
                          // 2. compress file and get file.
                          HudUtil.showBeautiful(context);
                          var result = await FlutterImageCompress.compressWithFile(
                              xFile!.path, quality: 80);

                          String fileNameWithExtension = xFile!.path
                              .split('/')
                              .last;
                          // String fileName = fileNameWithExtension.split('.').first;
                          String _title = fileNameWithExtension;

                          Uint8List uint8List = result!;
                          Digest fileMd5 = md5.convert(
                              oriFile.readAsBytesSync().sublist(1024, 5024));

                          // String urlString = "${getBaseUrlMap()[BaseUrl.development]}"+'/api/util/fileoss//upload/checkfile?fileMd5=${fileMd5.toString()}';
                          HttpEntity h = await HttpManager.getInstance().request(
                              url: "/util/fileoss/upload/checkfile?fileMd5=${fileMd5.toString()}",
                              method: Method.get) as HttpEntity;

                          String pathAndUrl = h.getOriData()["data"];
                          if (pathAndUrl.length == 0) {
                            Map<String, dynamic> params1 = {
                              'file': dio.MultipartFile.fromBytes(
                                  uint8List!, filename: 'image_}.png'),
                              'fileMd5': fileMd5
                            };
                            HttpEntity h8 = await HttpManager.getInstance().request(
                                url: '/util/fileoss/uploadOssVideoCover',
                                method: Method.file,
                                params: params1) as HttpEntity;
                            // this.cover = h8.getOriData()['data'];
                            // this.imgsUrl.add(this.cover);
                            // 按钮点击事件
                            albumEntity!.cover = h8.getOriData()['data'];
                            albumEntity!.name = textEditingController.text.length>0?textEditingController.text:albumEntity!.name;
                            String jsonObject = jsonEncode(albumEntity);

                            HttpEntity h2 = await HttpManager.getInstance().request(url: "/platform/album/updateAlbum",
                                method: Method.post,object:jsonObject) as HttpEntity;
                            HudUtil.dismiss();

                            Navigator.pop(context);

                          }},
                        elevation: 0,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8), // 设置圆角
                          side: BorderSide( // 设置边框
                            color: WcaoTheme.placeholder, // 边框颜色
                            width: 1.0, // 边框宽度
                          ),
                        ),

                        color: Colors.white, // 设置按钮颜色
                        // padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), // 设置内边距
                        child: const Text(
                          "选择修改",
                          style: TextStyle(

                            fontSize: 18, // 设置文字大小
                          ),
                        ),
                      )

                      ,




                    ],
                  )
              ),
              // SizedBox(
              //     child:  Row(
              //       mainAxisAlignment: MainAxisAlignment.center,
              //       children: [
              //         MaterialButton(
              //           onPressed: () async {
              //             if(textEditingController.text.length <=0) {
              //               return;
              //             }
              //             HudUtil.showBeautiful(context);
              //             User u = tokenController.user.value[0];
              //             u.description = textEditingController.text;
              //             Map<String,String> params = {
              //               "user":jsonEncode(u)
              //             };
              //             HttpEntity h2 = await HttpManager.getInstance().request(url: "/platform/user/updateUser",
              //                 method: Method.post,params: params,object: params["user"]) as HttpEntity;
              //             // 按钮点击事件
              //
              //             tokenController.updateUser();
              //             HudUtil.dismiss();
              //             Navigator.pop(context);
              //           },
              //           elevation: 0,
              //           shape: RoundedRectangleBorder(
              //             borderRadius: BorderRadius.circular(8), // 设置圆角
              //             side: BorderSide( // 设置边框
              //               color: WcaoTheme.placeholder, // 边框颜色
              //               width: 1.0, // 边框宽度
              //             ),
              //           ),
              //
              //           color: Colors.white, // 设置按钮颜色
              //           // padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), // 设置内边距
              //           child: Text(
              //             "更换名称",
              //             style: TextStyle(
              //
              //               fontSize: 18, // 设置文字大小
              //             ),
              //           ),
              //         )
              //
              //         ,
              //
              //
              //
              //
              //       ],
              //     )
              // ),




            ],
          ),):Text(""),

    );
  }


}
